using System;
using System.IO;
using System.Collections.Generic;
using Silvery.Loader;

namespace Silvery
{
    public interface IResStream : IDisposable
    {
        /// <summary>
        /// 资源Stream
        /// </summary>
        Stream ResouceStream { get; }
        /// <summary>
        /// 使用计数
        /// </summary>
        int UsingCount { get; }
        /// <summary>
        /// 调用的时间
        /// </summary>
        ITimer TimeSheet { get; }       
        /// <summary>
        /// 添加使用目标
        /// </summary>
        /// <param name="item"></param>
        void AddUsingTarget(object item);
        /// <summary>
        /// 移除使用目标
        /// </summary>
        /// <param name="item"></param>
        void RemoveUsingTarget(object item);
        /// <summary>
        /// 资源的Uri标记
        /// </summary>
        Uri ResouceUri { get; }
    }
    /// <summary>
    /// 一个标准的游戏资源
    /// </summary>
    public class ResStream : IResStream
    {
        public ResStream(Uri uri,Stream stream,object usingobject)
        {
            ResouceUri = uri;
            ResouceStream = stream;
            UsingList = new List<object>();
            UsingList.Add(usingobject);
            ResourceManager.Current.Add(this);
            TimeSheet = new CallTimer() ;
        }
        public Uri ResouceUri { get; private set; }
        public Stream ResouceStream
        {
            get;
            private set;
        }

        public int UsingCount
        {
            get { return UsingList.Count; }
        }

        public ITimer TimeSheet
        {
            get;
            private set;
        }

        public void Dispose()
        {
            if(UsingList.Count>0)
                for (int i = UsingList.Count-1; i >=0; i--)
                {
                    var item = UsingList[i] as ILoader;
                    if (item != null)
                    {
                        LoaderManager.Current.Remove(item);
                        item.Result = null;
                    }
                }
            UsingList.Clear();
            UsingList = null;
            if (ResouceStream != null)
            {
                ResouceStream.Close();
                ResouceStream.Dispose();
                ResouceStream = null;
            }
            
        }
        List<object> UsingList;
        public void AddUsingTarget(object item)
        {
            if (item == null)
                return;
            TimeSheet.Call();
            UsingList.Add(item);
        }
        public void RemoveUsingTarget(object item)
        {
            if(item!=null)
                UsingList.Remove(item);
        }
    }
}
